<template>
  <div class="app-container">
    <tab-selector :options="[{ label: '总人数', value: ' ' }]"></tab-selector>

    <el-form inline label-width="68px">
      <el-form-item label="到店时间">
        <date-picker :value="onClinicTime" @input="handleOnClinicTime" />
      </el-form-item>
      <!-- <el-form-item label="渠道">
        <el-cascader
          v-model="channel"
          style="width: 260px;"
          :options="channelOptions"
          :props="{ checkStrictly: true }"
          clearable
          @change="handleChannel"
        ></el-cascader>
      </el-form-item>-->
      <!-- <el-form-item>
        <el-button type="primary" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>-->
    </el-form>

    <el-row :gutter="10" class="mb20">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-edit"
          :disabled="!tableRadio"
          @click="handleModifyClinicTime"
        >修改到店时间</el-button>
        <modify-clinic-time
          v-model="modifyClinicTime.visible"
          :data="modifyClinicTime.data"
          @ok="getList"
        ></modify-clinic-time>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-edit"
          :disabled="!tableRadio"
          @click="handleUpdatePatientPanel"
        >修改个人信息</el-button>
        <update-patient-panel
          v-model="updatePatientPanel.visible"
          :patient="updatePatientPanel.patient"
          @ok="getList"
        ></update-patient-panel>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-edit"
          :disabled="!tableRadio"
          @click="handleModifyMedium"
        >修改媒介</el-button>
        <modify-medium v-model="modifyMedium.visible" :data="modifyMedium.data" @ok="getList"></modify-medium>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-edit"
          :disabled="!tableRadio"
          @click="handleModifyDoctor"
        >修改医生</el-button>
        <modify-doctor v-model="modifyDoctor.visible" :data="modifyDoctor.data" @ok="getList"></modify-doctor>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-edit"
          :disabled="!tableRadio"
          @click="handleAddPhone"
        >添加电话</el-button>
        <modify-phone v-model="modifyPhone.visible" :data="modifyPhone.data" @ok="getList"></modify-phone>
        <el-button
          type="primary"
          icon="el-icon-edit"
          :disabled="!tableRadio"
          @click="handleEditPhone"
        >修改电话</el-button>
        <edit-phone v-model="editPhone.visible" :data="editPhone.data" @ok="getList"></edit-phone>
      </el-col>
      <el-col :span="1.5">
        <columns-filter-button />
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      border
      :data="personList"
      stripe
      :height="clientHeight"
      :max-height="clientHeight"
      @row-dblclick="handleDetails"
      @cell-click="handleCellClick"
      @filter-change="handleFilterChange"
    >
      <el-table-column width="55" align="center" fixed="left">
        <template slot-scope="scope">
          <el-radio v-model="tableRadio" :label="scope.row">
            <i></i>
          </el-radio>
        </template>
      </el-table-column>
      <columns-filter-view>
        <el-table-column
          label="病例号"
          align="center"
          prop="yiyaClinicPerson.caseNumber"
          min-width="150"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view label="头像">
        <el-table-column label="头像" align="center" prop="imageUrl" :min-width="'头像'">
          <avatar-image slot-scope="scope" :patient="scope.row.yiyaClinicPerson"></avatar-image>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column label="姓名" align="center" min-width="100">
          <div slot-scope="scope" style="cursor: pointer">{{ scope.row.yiyaClinicPerson.name }}</div>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column label="手机号" align="center" min-width="180">
          <hover-phone slot-scope="scope" :type="1" :items="scope.row.yiyaClinicPerson" />
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column label="性别" align="center" prop="yiyaClinicPerson.sex">
          <template slot-scope="scope">
            {{
            sexEnum[scope.row.yiyaClinicPerson.sex]
            }}
          </template>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column label="年龄" align="center" prop="yiyaClinicPerson.age"></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="一级渠道"
          align="center"
          prop="yiyaClinicPerson.channelFirst"
          :show-overflow-tooltip="true"
          :min-width="'到店状态'.length * 30"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="二级渠道"
          align="center"
          prop="yiyaClinicPerson.channelSecond"
          :show-overflow-tooltip="true"
          :min-width="'到店状态'.length * 30"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="三级渠道"
          align="center"
          prop="yiyaClinicPerson.channelThird"
          :show-overflow-tooltip="true"
          :min-width="'到店状态'.length * 30"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="客户状态"
          align="center"
          prop="yiyaClinicPerson.personStatus"
          :min-width="'到店状态'.length * 30"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="开单状态"
          align="center"
          prop="yiyaClinicPerson.billingStatus"
          column-key="billingStatus"
          :filters="billingStatusOptions"
          min-width="100"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="扫码状态"
          align="center"
          prop="yiyaClinicPerson.scanStatus"
          :min-width="'到店状态'.length * 30"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="已交金额"
          align="center"
          prop="yiyaClinicPerson.overMoney"
          :min-width="'到店状态'.length * 30"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column label="欠费" align="center" prop="yiyaClinicPerson.arrearage"></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="TC"
          align="center"
          prop="yiyaAppointment.tcName"
          min-width="100"
          column-key="tcId"
          :filters="tcOptions"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="医生"
          align="center"
          prop="yiyaAppointment.doctorName"
          min-width="100"
          column-key="doctorId"
          :filters="doctorOptions"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="到店时间"
          align="center"
          prop="yiyaAppointment.onClinicTime"
          width="180"
        >
          <template slot-scope="scope">
            {{
            scope.row.yiyaAppointment.onClinicTime &&
            dayjs(scope.row.yiyaAppointment.onClinicTime).format(
            'YYYY-MM-DD HH:mm:ss'
            )
            }}
          </template>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="初诊时间"
          align="center"
          prop="yiyaClinicPerson.firstDiagnoseTime"
          width="180"
        >
          <template slot-scope="scope">
            {{
            scope.row.yiyaClinicPerson.firstDiagnoseTime &&
            dayjs(scope.row.yiyaClinicPerson.firstDiagnoseTime).format(
            'YYYY-MM-DD HH:mm:ss'
            )
            }}
          </template>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="黄页编号"
          align="center"
          prop="yiyaClinicPerson.yellowCode"
          :min-width="'到店状态'.length * 30"
        />
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="备注"
          align="center"
          prop="yiyaAppointment.remarks"
          min-width="180"
          :show-overflow-tooltip="true"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="网络咨询师"
          align="center"
          prop="yiyaClinicPerson.networkCounselor"
          min-width="120"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="一级媒介"
          align="center"
          prop="yiyaClinicPerson.mediumFirst"
          :show-overflow-tooltip="true"
          :min-width="'到店状态'.length * 30"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="二级媒介"
          align="center"
          prop="yiyaClinicPerson.mediumSecond"
          :show-overflow-tooltip="true"
          :min-width="'到店状态'.length * 30"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="三级媒介"
          align="center"
          prop="yiyaClinicPerson.mediumThird"
          :show-overflow-tooltip="true"
          :min-width="'到店状态'.length * 30"
        ></el-table-column>
      </columns-filter-view>
      <empty slot="empty"></empty>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    ></pagination>

    <user-matcher-result contains-temp-clinic-person @update="getList"></user-matcher-result>
    <user-matcher-appointment @submit="getList"></user-matcher-appointment>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { mapState } from 'vuex'
import { listChannel } from '@/api/erp/channel'
import { listStaff } from '@/api/services/common'
import { allListAppointment } from '@/api/services/appointment'
import { encode, listToTreeOptions } from '@/utils/utils'
import {
  getThisWeekStartWithEnd,
  getTodayStartWithEnd,
  getTomorrowStartWithEnd,
} from '@/utils/date'
import { billingStatusOptions } from '@/utils/options'
import { sexEnum } from '@/utils/enums'

import TabSelector from '@/components/yiya/TabSelector'
import TablePhone from '@/components/yiya/TablePhone'
import {
  ColumnsFilterButton,
  ColumnsFilterView,
} from '@/components/yiya/TableColumnsFilter'
import DatePicker from '@/components/yiya/DatePicker/index'

const QUERY_PARAMS = {
  pageNum: 1,
  pageSize: 50,
  orderByColumn: 'onClinicTime',
  isAsc: 'desc',
  personStatus: undefined,
  startOnClinicTime: undefined,
  endOnClinicTime: undefined,
  channelFirst: undefined,
  channelSecond: undefined,
  channelThird: undefined,
  departments: undefined,
  billingStatus: undefined,
  tcId: undefined,
  doctorId: undefined,
}

export default {
  name: 'ShopModify',
  components: {
    DatePicker,
    Empty: () => import('@/components/yiya/Empty'),
    TabSelector,
    HoverPhone: () => import('@/components/yiya/hoverPhone'),
    ColumnsFilterButton,
    ColumnsFilterView,
    UpdatePatientPanel: () => import('../components/UpdatePatientPanel'),
    ModifyClinicTime: () => import('./ModifyClinicTime'),
    ModifyMedium: () => import('./ModifyMedium'),
    ModifyDoctor: () => import('./ModifyDoctor'),
    ModifyPhone: () => import('./ModifyPhone/index'),
    EditPhone: () => import('./ModifyPhone/EditPhone'),
    UserMatcherResult: () => import('@/components/yiya/UserMatcherResult'),
    UserMatcherAppointment: () =>
      import('@/components/yiya/UserMatcherAppointment'),
    AvatarImage: () => import('@/components/yiya/avatarImage'),
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      tableRadio: null,
      clientHeight: document.body.clientHeight - 325,
      // 总条数
      total: 0,
      // 到店患者信息表格数据
      personList: [],
      // 是否显示弹出层
      open: false,
      // 患者信息
      patient: {},
      // 查询参数
      queryParams: {},
      onClinicTime: undefined,
      channelList: [],
      channel: [],
      doctorList: [],
      tcList: [],
      modifyClinicTime: {
        visible: false,
        data: {},
      },
      updatePatientPanel: {
        visible: false,
        patient: {},
      },
      modifyMedium: {
        visible: false,
        data: {},
      },
      modifyDoctor: {
        visible: false,
        data: {},
      },
      modifyPhone: {
        visible: false,
        data: {},
      },
      editPhone: {
        visible: false,
        data: {},
      },
    }
  },
  computed: {
    ...mapState({
      clinicId: (state) => state.clinic.clinicId,
    }),
    dayjs() {
      return dayjs
    },
    sexEnum() {
      return sexEnum
    },
    billingStatusOptions() {
      return billingStatusOptions.map(({ label, value }) => ({
        text: label,
        value,
      }))
    },
    doctorOptions() {
      return this.doctorList.map(({ userName, userId }) => ({
        text: userName,
        value: userId,
      }))
    },
    tcOptions() {
      return this.tcList.map(({ userName, userId }) => ({
        text: userName,
        value: userId,
      }))
    },
    channelOptions() {
      return [
        {
          label: '直接上门',
          value: '直接上门',
          children: [
            {
              label: '直接上门',
              value: '直接上门',
              children: [{ label: '直接上门', value: '直接上门' }],
            },
          ],
        },
        ...this.channelList,
      ]
    },
  },
  mounted() {
    this.queryParams = {
      ...QUERY_PARAMS,
      ...this.$route.query,
      clinicId: +this.clinicId,
    }
    this.handleOnClinicTime(getTodayStartWithEnd())
    this.getDoctorList()
    this.getTcList()
    this.getChannelOptions()
  },
  methods: {
    /** 查询到店患者信息列表 */
    async getList() {
      try {
        this.loading = true
        this.tableRadio = null
        const { rows, total } = await allListAppointment(this.queryParams)
        this.personList = rows
        this.total = total
      } finally {
        this.loading = false
      }
    },
    /**
     * 获取医生列表
     */
    async getDoctorList() {
      const { data } = await listStaff({
        deptId: +this.clinicId,
        postname: '医生',
      })
      this.doctorList = data
    },
    /**
     * 获取tc列表
     */
    async getTcList() {
      const { data } = await listStaff({
        deptId: +this.clinicId,
        postname: 'TC',
      })
      this.tcList = data
    },
    /**
     * 查看按钮操作
     */
    handleDetails(row) {
      this.$router.push(
        `/shop/details?id=${row.yiyaClinicPerson.id}&redirect=${encode({
          path: this.$route.path,
          query: this.queryParams,
        })}`
      )
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams.departments = undefined
      this.queryParams.billingStatus = undefined
      this.queryParams.tcId = undefined
      this.queryParams.doctorId = undefined
      this.handleOnClinicTime(getTodayStartWithEnd())
      this.handleQuery()
    },
    /**
     * 修改到店时间
     */
    handleModifyClinicTime() {
      this.modifyClinicTime = {
        visible: true,
        data: {
          id: this.tableRadio.yiyaAppointment.id,
          date: this.tableRadio.yiyaAppointment.onClinicTime,
        },
      }
    },
    /**
     * 修改个人信息
     */
    handleUpdatePatientPanel() {
      this.updatePatientPanel = {
        visible: true,
        patient: this.tableRadio.yiyaClinicPerson,
      }
    },
    /**
     * 添加电话
     */
    handleAddPhone() {
      if (!this.tableRadio.yiyaClinicPerson.phoneNumber2) {
        this.modifyPhone = {
          visible: true,
          data: {
            id: this.tableRadio.yiyaClinicPerson.id,
            phoneNumber2: this.tableRadio.yiyaClinicPerson.phoneNumber2,
          },
        }
      } else {
        this.msgWarning('电话2已存在')
      }
    },
    /**
     *  修改电话
     * */
    async handleEditPhone() {
      console.log(this.tableRadio.yiyaClinicPerson)
      this.editPhone = {
        visible: true,
        data: {
          id: this.tableRadio.yiyaClinicPerson.id,
          phoneNumber: '',
          phoneOwnership: this.tableRadio.yiyaClinicPerson.phoneOwnership,
          phoneOwnership2: this.tableRadio.yiyaClinicPerson.phoneOwnership2,
          phoneNumber2: '',
        },
      }
    },

    handleModifyMedium() {
      const {
        mediumFirst,
        mediumSecond,
        mediumThird,
      } = this.tableRadio.yiyaClinicPerson
      this.modifyMedium = {
        visible: true,
        data: {
          id: this.tableRadio.yiyaClinicPerson.id,
          medium: [mediumFirst, mediumSecond, mediumThird],
        },
      }
    },
    /**
     * 修改医生
     */
    handleModifyDoctor() {
      this.modifyDoctor = {
        visible: true,
        data: {
          id: this.tableRadio.yiyaAppointment.id,
          doctorId: this.tableRadio.yiyaAppointment.doctorId,
        },
      }
    },
    handleFilterChange(e) {
      const [key, value] = Object.entries(e)[0]
      this.queryParams[key] = value.join(',')
      this.handleQuery()
    },
    async getChannelOptions() {
      const { rows } = await listChannel({
        pageNum: 1,
        pageSize: 10000000,
      })
      this.channelList = listToTreeOptions(rows, ({ pid, id, name }) => ({
        parentId: pid,
        id,
        label: name,
        value: name,
      }))
    },
    handleCellClick(row, column) {
      if (column.label === '姓名') {
        this.handleDetails(row)
      }
    },
    handleChannel(e) {
      ;[
        this.queryParams.channelFirst,
        this.queryParams.channelSecond,
        this.queryParams.channelThird,
      ] = e
      this.handleQuery()
    },
    handleOnClinicTime([start, end]) {
      ;[start, end] = [dayjs(start).startOf('day'), dayjs(end).endOf('day')]
      this.onClinicTime = [start, end]
      this.queryParams.startOnClinicTime = start.format('YYYY-MM-DD HH:mm:ss')
      this.queryParams.endOnClinicTime = end.format('YYYY-MM-DD HH:mm:ss')
      this.handleQuery()
    },
  },
}
</script>
